﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace TBlogAssist
{
    public partial class MainForm : Form
    {
        private BackgroundWorker worker = new BackgroundWorker();
        private string access_token;
        private string oauth_consumer_key;
        private string openid;

        public MainForm()
        {
            InitializeComponent();

            worker.WorkerReportsProgress = true;
            worker.DoWork += WorkerOnDoWork;
            worker.ProgressChanged += WorkerOnProgressChanged;
        }

        private void WorkerOnProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            switch (e.ProgressPercentage)
            {
                case 10:
                    WorkingPane.Visible = true;
                    break;
                case 30:
                    AppId.Text = oauth_consumer_key;
                    OpenId.Text = openid;
                    break;
                case 40:
                    NickName.Text = e.UserState as string;
                    break;
                case 100:
                    Avatar.ImageLocation = e.UserState as string;
                    break;
            }
        }

        private void WorkerOnDoWork(object sender, DoWorkEventArgs e)
        {
            worker.ReportProgress(10);

            using (var wc = new WebClient())
            {
                // get app_id and open_id               
                var buffer = wc.DownloadString("https://graph.qq.com/oauth2.0/me?access_token=" + access_token);

                // callback( {"client_id":"100442012","openid":"ED14222A17FC7A9B392CAA0B96299C13"} );
                var tmp = buffer.Split('"');

                oauth_consumer_key = tmp[3].Substring(3); // this is special for tudou's app id
                openid = tmp[7];
                worker.ReportProgress(30);

                // get_user_info
                buffer = wc.DownloadString(string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, oauth_consumer_key, openid));
                tmp = buffer.Split('"');
                worker.ReportProgress(40, tmp[9]); //bug: garbled nickname

                var avatarUrl = tmp[32].Replace(@"\/", "/");
                worker.ReportProgress(100, avatarUrl);
            }
        }

        private void QQLoginClick(object sender, EventArgs e)
        {
            QQLogin.Hide();

            var browser = new WebBrowser();
            browser.Navigating += BrowserNavigating;
            browser.DocumentCompleted += BrowserOnDocumentCompleted;
            browser.Navigate("https://graph.qq.com/oauth2.0/authorize?client_id=200003&response_type=token&scope=all&redirect_uri=http://www.tudou.com/");
            browser.Dock = DockStyle.Fill;

            this.Controls.Add(browser);
        }

        private void BrowserOnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs webBrowserDocumentCompletedEventArgs)
        {
            var browser = sender as WebBrowser;
            var data = "";

            // find div#request_site, change site image and label
            var div = browser.Document.GetElementById("request_site");
            if (div != null)
            {
                div.Children[1].SetAttribute("src", data); // img
                div.Children[2].SetAttribute("href", "javascript://void(0)"); // a
                div.Children[2].InnerText = this.Text; // a
            }
        }

        private void BrowserNavigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            var browser = sender as WebBrowser;

            // get access_token from url
            if (browser.Url != null && browser.Url.ToString().Contains("access_token"))
            {
                browser.Hide();
                e.Cancel = true;

                var url = browser.Url.ToString();
                var begin = url.IndexOf("access_token") + "access_token".Length + 1;
                var end = url.IndexOf("&", begin);
                access_token = url.Substring(begin, end - begin);

                worker.RunWorkerAsync();

                browser.Navigating -= BrowserNavigating;
                browser.Navigate("about:blank");
            }
        }

        private void AddTBlogClick(object sender, EventArgs e)
        {
            /*
            POST https://graph.qq.com/t/add_t
             
            content:微博内容
            oauth_consumer_key:100330589
            access_token:BFCCC21B87C251D3F8BB6706342E4F0B
            openid:91160EBBC07557CE8EB89CB19BAD1702
            format:json
             */

            var data = string.Format("content={0}&oauth_consumer_key={1}&access_token={2}&openid={3}&format=json",
                                     HttpUtility.UrlEncode(TBlogText.Text), oauth_consumer_key, access_token, openid);
            var req = WebRequest.CreateHttp("https://graph.qq.com/t/add_t");
            req.Method = "POST";
            var buffer = Encoding.UTF8.GetBytes(data);
            req.GetRequestStream().Write(buffer, 0, buffer.Length);
            req.GetResponse();

            MessageBox.Show("OK");
        }
    }
}
